package com.example.interceptor.recursion;

import com.example.interceptor.Request;
import com.example.interceptor.Response;
import com.example.interceptor.Target;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 目标调用类
 */
public class TargetInvocation {
    private final List<Interceptor> interceptorList = new ArrayList<>();
    private Iterator<Interceptor> iterator;
    private Request request;
    private Target target;


    public static void main(String[] args) {
        TargetInvocation targetInvocation = new TargetInvocation();
        targetInvocation.addInterceptor(new LogInterceptor());
        targetInvocation.addInterceptor(new AuditInterceptor());
        targetInvocation.setRequest(new Request());
        targetInvocation.setTarget(req -> {
            return new Response();
        });
        targetInvocation.invoke();
    }


    public void addInterceptor(Interceptor interceptor) {
        interceptorList.add(interceptor);
        iterator = interceptorList.iterator();
    }

    public Response invoke() {
        if (iterator != null && iterator.hasNext()) {
            Interceptor interceptor = iterator.next();
            interceptor.intercept(this); //递归调用invoke
        }
        return target.execute(request);
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void setTarget(Target target) {
        this.target = target;
    }
}
